package ac.github.oa.internal.core.item.generator

import ac.github.oa.api.event.item.ItemCreateGroupGeneratorEvent
import ac.github.oa.internal.core.item.Item
import ac.github.oa.internal.core.item.ItemPlant
import org.bukkit.entity.LivingEntity
import org.bukkit.inventory.ItemStack
import taboolib.common.LifeCycle
import taboolib.common.platform.Awake
import taboolib.common.util.random
import taboolib.common5.Coerce
import taboolib.common5.cdouble
import taboolib.common5.cint
import taboolib.common5.clong

@Awake(LifeCycle.LOAD)
class GroupGenerator : ItemGenerator {
    override val name: String
        get() = "group"

    fun Item.items(): List<String> {
        return config.getStringList("items")
    }

    fun Item.getItem(entity: LivingEntity?): Pair<String, Int> {
        val items = items()
        val string = items.random()
        val split = string.split(" ")
        val event = ItemCreateGroupGeneratorEvent(entity, split[0], split[2].cdouble, split[1].cint)
        if (event.call() && random(event.chance)) {
            return Pair(event.id, event.amount)
        }
        return getItem(entity)
    }

    override fun build(entity: LivingEntity?, item: Item, map: MutableMap<String, String>): ItemStack {
        val pair = item.getItem(entity)
        return ItemPlant.build(entity, pair.first, map)?.also {
            it.amount = pair.second
        } ?: error("Item ${pair.first} not found.")
    }
}